package com.zx.idc.backend.gui.api.ftp.basic;

import com.jcraft.jsch.Session;
import com.zx.idc.common.pool.Pool;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * ftp 对象校验器
 *
 * @author rxliuli
 */
public class BasicFtpClientValidator implements Pool.Validator<FTPClient> {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @Override
    public boolean valid(FTPClient ftpClient) {
        try {
            //发送noop命令保持连接 若是发送抛异常证明连接已经关闭
            ftpClient.sendNoOp();
        } catch (IOException e) {
            return false;
        }
        int replyCode = ftpClient.getReplyCode();
        return !FTPReply.isNegativePermanent(replyCode) && !FTPReply.isNegativeTransient(replyCode);
    }

    @Override
    public void invalidate(FTPClient ftpClient) {
        if (ftpClient != null) {
            try {
                ftpClient.disconnect();
                log.debug("关闭ftp连接结果:{}", ftpClient.getReplyCode());
            } catch (IOException e) {
                log.error("关闭ftp连接失败", e.getMessage());
            }
        }
    }
}
